package ywpt.web.action.config;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;

import ywpt.components.acegi.domain.Operation;
import ywpt.core.Constants;
import ywpt.core.SystemMessage;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.util.DateTools;
import ywpt.core.util.StringTools;
import ywpt.core.web.BaseAction;
import ywpt.model.CommonTypes;
import ywpt.service.config.CommonTypesService;
import ywpt.web.common.OperationConstants;
import ywpt.web.common.PublicFunction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class CommonTypesAction extends BaseAction implements Preparable,ModelDriven<CommonTypes>{

	/**
	 * 锟斤拷锟斤拷锟斤拷息锟斤拷锟斤拷Action
	 */
	private static final long serialVersionUID = 6866943973266406099L;
	protected final Log			log	= LogFactory.getLog(CommonTypesAction.class);
	private Long				id;
	private String				townId;
	private String				type;
	private List<CommonTypes>	commonTypesList	= new ArrayList<CommonTypes>();
	private CommonTypes			commonTypes;
	private String				fieldId;
	private String				fieldCode;
	private String				fieldType;
	private String				searchString;
	private CommonTypesService  commonTypesService;
	protected static int		DEFAULT_PAGE_SIZE	= 20;
	protected static String		ENC_ALGORITHM		= "MD5";
	private boolean[] popedom=new boolean[Constants.POPEDOM_LEN];
	private int version;

	@Override
	public void prepare() throws Exception {
		if(getId()!=null)
			this.commonTypes=commonTypesService.getEntityById(getId());
		else
			this.commonTypes=new CommonTypes();
		HashMap<String,Operation> oper=this.getOperMapByUser(this.getCurrentUser());
		PublicFunction.getOperationPopedom(oper,popedom,OperationConstants.CONFIG_commonTypes);
	}

	@Override
	public CommonTypes getModel() {
		return commonTypes;
	}

	protected void showInformation()
	{		
	}
	
	protected void getData(DetachedCriteria query)
	{   

		query.add(Restrictions.eq("deleteFlag", false));
		int totalRows=RequestUtils.getTotalRowsFromRequest(getRequest());
		if(totalRows<0)
		{
			totalRows=commonTypesService.getEntityCountByCriteria(query);
		}
		int[] rowStartEnd=RequestUtils.getRowStartEnd(getRequest(),totalRows,
				DEFAULT_PAGE_SIZE,0);
		Limit limit=RequestUtils.getLimit(getRequest(),"ec",totalRows,
				DEFAULT_PAGE_SIZE);
		int pageSize=limit.getCurrentRowsDisplayed();	
		query.addOrder(Order.asc("code"));
		query.setProjection(null);
		commonTypesList.addAll(commonTypesService.getEntitys(query,
				pageSize,rowStartEnd[0]));
	}
	
	
	public String execute()
	{
		return null;
	}

	public String list()
	{
		commonTypesList.clear();
		DetachedCriteria query=DetachedCriteria.forClass(CommonTypes.class);		
		if (!StringTools.isNullOrSpace(searchString))
		{	try 
			{
				return this.search();
			} 
			catch (Exception e) 
			{
				this.addActionMessage(SystemMessage.SEARCH_ERROR);
				return SUCCESS;
			}
		}
		this.getData(query);
		return SUCCESS;
	}

	public String search() throws Exception
	{
		commonTypesList.clear();
		DetachedCriteria query=DetachedCriteria.forClass(CommonTypes.class);
		if(!StringTools.isNullOrSpace(fieldCode))
		{
			try
			{
				if(fieldCode.indexOf(".")!=-1)
				{
					String object=fieldCode.substring(0,fieldCode.indexOf("."));
					String property=fieldCode.substring(fieldCode.indexOf(".")+1);
					query.createAlias(object,object);
					if(this.fieldType.equals("date"))
					{
						query.add(Restrictions
								.eq(object+"."+property,DateTools.strToDate(
										this.getSearchString(),"yyyy-MM-dd")));
					}
					else if(this.fieldType.equals("digital"))
					{
						query.add(Restrictions.eq(object+"."+property,this
								.getSearchString()));
					}
					else if(this.fieldType.equals("int"))
					{
						query.add(Restrictions.eq(object+"."+property,Integer
								.parseInt(this.getSearchString())));
					}
					else if(this.fieldType.equals("boolean"))
					{
						query.add(Restrictions.eq(object+"."+property,Boolean
								.valueOf(this.getSearchString())));
					}
					else
					{
						query.add(Restrictions.like(object+"."+property,"%"
								+this.getSearchString()+"%"));
					}
				}
				else
				{
					if(this.fieldType.equals("date"))
					{
						query.add(Restrictions
								.eq(fieldCode,DateTools.strToDate(this
										.getSearchString(),"yyyy-MM-dd")));
					}
					else if(this.fieldType.equals("digital"))
					{
						query.add(Restrictions.eq(fieldCode,this
								.getSearchString()));
					}
					else if(this.fieldType.equals("int"))
					{
						query.add(Restrictions.eq(fieldCode,Integer
								.parseInt(this.getSearchString())));
					}
					else if(this.fieldType.equals("boolean"))
					{
						query.add(Restrictions.eq(fieldCode,Boolean
								.valueOf(this.getSearchString())));
					}
					else
					{
						query.add(Restrictions.like(fieldCode,"%"
								+this.getSearchString()+"%"));
					}
				}
			}
			catch(Exception e)
			{
				this.addActionMessage(SystemMessage.CONDITION_FORMAT_ERROR);
				return SUCCESS;
			}
		}
		this.getData(query);
		return SUCCESS;
	}
	
	public String query()
	{
		commonTypesList.clear();
		DetachedCriteria query=DetachedCriteria.forClass(CommonTypes.class);		
		this.getData(query);
		return SUCCESS;
	}

	@SkipValidation
	public String input()
	{    
		return INPUT;
	}
	
	@SuppressWarnings("unchecked")
	public String edit()
	{
		commonTypes=commonTypesService.getEntityById(id);
		showInformation();
		return INPUT;
	}
	
	@SuppressWarnings("unchecked")
	public String save() throws ServletException
	{  
		commonTypes.setUpdateDate(new Date());
		commonTypes.setUpdater(this.getCurrentUser().getFullName());
		try
		{
			if(id==null)
			{
				commonTypesService.save(commonTypes);
				this.addActionMessage(SystemMessage.SAVE_SUCCESS);
			}
			else
			{
				if(!commonTypes.isCheckFlag())
				{
					if(this.getVersion()==commonTypes.getVersion())
					{
						commonTypesService.update(commonTypes);
						this.addActionMessage(SystemMessage.UPDATE_SUCCESS);
					}
					else
						this.addActionMessage(SystemMessage.UPDATE_FAIL);
				}
				else
					this.addActionMessage(SystemMessage.AUDITING_SAVE);
			}			
		}	
		catch (UniqueConstraintException e) 
		{
			this.addActionError(SystemMessage.SAVE_FAIL+e.getMessage());
			return INPUT;
		}
		showInformation();
		return SUCCESS;
	}

	public String check()
	{
		if(id==null){
			this.addActionMessage(SystemMessage.NO_OBJECT);
			
		}else{
		commonTypes=commonTypesService.getEntityById(id);
		if(!commonTypes.isCheckFlag())
		{
			commonTypes.setChecker(this.getCurrentUser().getFullName());
			commonTypes.setCheckDate(DateTools.getDateTypeDate());
			commonTypes.setCheckFlag(true);
			commonTypesService.update(commonTypes);
			this.addActionMessage(SystemMessage.AUDITING_SUCCESS);
		}
		else
			this.addActionMessage(SystemMessage.AUDITING_REPEAT);
		
		}
		showInformation();
		return SUCCESS;
	}
	
	public String discheck()
	{
		if(id==null){
			this.addActionMessage(SystemMessage.NO_OBJECT);
			
		}else{
		commonTypes=commonTypesService.getEntityById(id);
		if(commonTypes.isCheckFlag())
		{
			commonTypes.setChecker(null);
			commonTypes.setCheckDate(null);
			commonTypes.setCheckFlag(false);
			commonTypesService.update(commonTypes);
			this.addActionMessage(SystemMessage.DISAUDITING_SUCCESS);
		}
		else
			this.addActionMessage(SystemMessage.DISAUDITING_REPEAT);
		
		}
		showInformation();
		return SUCCESS;
	}
	
	public String delete()
	{
		if(id!=null)
		{
			if(!commonTypes.isCheckFlag())
				commonTypesService.remove(id);
			else
			{
				this.addActionMessage(SystemMessage.DELETE_AUDITING_FAIL);
				showInformation();
				return INPUT;
			}
		}
		else
		{
			this.addActionMessage(SystemMessage.NO_OBJECT);
			showInformation();
			return INPUT;
		}			
		return SUCCESS;
	}
	
	public String select()
	{
		DetachedCriteria query=DetachedCriteria.forClass(CommonTypes.class);
		if(!StringTools.isNullOrSpace(type)){
			query.createAlias("town", "town").add(
			        Restrictions.eq("town.id", 
			        Long.parseLong(type)));
			//query.add(Restrictions.eq("type",type));
		}
		query.add(Restrictions.eq("deleteFlag", false));
		commonTypesList.addAll(commonTypesService.getEntitys(query));
		return SUCCESS;
	}
	
	
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getTownId() {
		return townId;
	}

	public void setTownId(String townId) {
		this.townId = townId;
	}

	public List<CommonTypes> getCommonTypesList() {
		return commonTypesList;
	}

	public void setCommonTypesList(List<CommonTypes> commonTypesList) {
		this.commonTypesList = commonTypesList;
	}

	public CommonTypes getCommonTypes() {
		return commonTypes;
	}

	public void setCommonTypes(CommonTypes commonTypes) {
		this.commonTypes = commonTypes;
	}

	public String getFieldId() {
		return fieldId;
	}

	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}

	public String getFieldCode() {
		return fieldCode;
	}

	public void setFieldCode(String fieldCode) {
		this.fieldCode = fieldCode;
	}

	public String getFieldType() {
		return fieldType;
	}

	public void setFieldType(String fieldType) {
		this.fieldType = fieldType;
	}

	public String getSearchString() {
		return searchString;
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
	}

	public CommonTypesService getCommonTypesService() {
		return commonTypesService;
	}

	public void setCommonTypesService(CommonTypesService commonTypesService) {
		this.commonTypesService = commonTypesService;
	}

	public boolean[] getPopedom() {
		return popedom;
	}

	public void setPopedom(boolean[] popedom) {
		this.popedom = popedom;
	}

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public Log getLog() {
		return log;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	
	
	
}
